package com.sh.suhe.utildemos.getImageColor;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RelativeLayout;

public class ColorBgView extends RelativeLayout {
    private String TAG = ColorBgView.class.getSimpleName();
    int startColor,endColor;
    LinearGradient mLinearGradient;
    Paint mPaint;

    public ColorBgView(Context context) {
        super(context);
        init();
    }

    public ColorBgView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ColorBgView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public ColorBgView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }
    private void init() {
        startColor = Color.RED;
        endColor = Color.BLUE;
        mLinearGradient = new LinearGradient(0,0,getMeasuredWidth() , getMeasuredHeight()
                , startColor, endColor, Shader.TileMode.MIRROR);
        mPaint = new Paint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mLinearGradient == null) {
            return;
        }
        Log.e(TAG, "getMeasuredWidth(): " + getMeasuredWidth() + " getMeasuredHeight(): " + getMeasuredHeight());
        mPaint.setShader(mLinearGradient);
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint);

    }

    public void setColor(int darkColor, int color) {
        Log.e(TAG, "darkColor: " + darkColor + " color: " + color);
        startColor = darkColor;
        endColor = color;
        mLinearGradient = new LinearGradient(0,0, 0 , getMeasuredHeight()
                , startColor, endColor, Shader.TileMode.REPEAT);
        invalidate();
    }
}
